package com.marquis.cloud.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.marquis.cloud.config.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 向Spring容器中注入DruidConfiguration
 */
@Configuration
public class DruidConfiguration {

    @Autowired
    private Properties properties;

    @Bean     //声明其为Bean实例
    @Primary //@Primary 注解作用是当程序选择dataSource时选择被注解的这个
    @RefreshScope //刷新数据源
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setQueryTimeout(0);
        datasource.setUrl(properties.getDbUrl());
        datasource.setUsername(properties.getUsername());
        datasource.setPassword(properties.getPassword());
        datasource.setDriverClassName(properties.getDriverClassName());
        datasource.setInitialSize(properties.getInitialSize());
        datasource.setMinIdle(properties.getMinIdle());
        datasource.setMaxActive(properties.getMaxActive());
        datasource.setMaxWait(properties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(properties.getValidationQuery());
        datasource.setTestWhileIdle(properties.isTestWhileIdle());
        datasource.setTestOnBorrow(properties.isTestOnBorrow());
        datasource.setTestOnReturn(properties.isTestOnReturn());
        datasource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        try {
            datasource.setFilters(properties.getFilters());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }
}